<?php

// @todo we should use PDO
class DB
{
    private $config = array();
    protected $isConnected = false;
    protected $DB;

    public function __construct($config = array())
    {
        $this->config = $config;
    }

    public function connect()
    {
        try {
            $this->DB = new PDO('mysql:host=' . $this->config['host'] . ';dbname=' . $this->config['name'], $this->config['user'], $this->config['password']);
            $this->DB->beginTransaction();
        }
        catch(PDOException $e) {
            echo $e->getMessage();
        }
        $this->isConnected = true;
    }

    public function push($linkId, $data = array(), $isDomain, $period = 7) {
        if (!$this->isConnected)
            $this->connect();

        $table = $isDomain ? 'domain' : 'domain_link';
        $rankTable = $isDomain ? 'domain_rank' : 'domain_link_history';
        $idField = $isDomain ? 'domain_id' : 'domain_link_id';

        $data['date'] = date('Y-m-d');
        $insertKeys = '`' . implode('`, `', array_keys($data)) . '`';
        $insertValues = '"' . implode('", "', $data) . '"';
        $updateAttributes = array();

        foreach ($data as $key => $value) {
            $updateAttributes[] = '`' . $key . '` = "' . $value . '"';
        }
        $updateAttributes = implode(', ', $updateAttributes);
        try {
            $this->DB->exec('INSERT INTO ' . $rankTable . ' (' . $idField . ', ' . $insertKeys . ')
                VALUES (' . $linkId . ', ' . $insertValues . ')
                ON DUPLICATE KEY UPDATE ' . $updateAttributes . ';
                UPDATE ' . $table . '
                SET `check_at` = "' . date('Y-m-d', time() + 3600 * 24 * $period) . '"
                WHERE id = ' . $linkId . ';');
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

     public function setScheduler($linkId, $isDomain, $period = 7) {
        if (!$this->isConnected)
            $this->connect();

        $table = $isDomain ? 'domain' : 'domain_link';

        try {
            $this->DB->exec('UPDATE ' . $table . '
                SET `check_at` = "' . date('Y-m-d', time() + 3600 * 24 * $period) . '"
                WHERE id = ' . $linkId . ';');
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

     public function setBadResult($linkId, $isDomain, $interval = 7) {
        if (!$this->isConnected)
            $this->connect();

        $table = $isDomain ? 'domain' : 'domain_link';

        try {
            $this->DB->exec('UPDATE ' . $table . '
                SET `check_at` = "' . date('Y-m-d', time() + 3600 * 24 * $interval) . '", `good_result_at` = NULL
                WHERE id = ' . $linkId . ';');
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    public function setGoodResult($linkId, $isDomain) {
        if (!$this->isConnected)
            $this->connect();

        $table = $isDomain ? 'domain' : 'domain_link';

        try {
            $this->DB->exec('UPDATE ' . $table . '
                SET `good_result_at` = "' . date('Y-m-d') . '"
                WHERE id = ' . $linkId . ' AND (`good_result_at` IS NOT NULL OR `check_at` <= "' . date('Y-m-d') . '" OR `check_at` IS NULL);');
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    public function setAlerts($linkId, $alerts = array())
    {
        if (!$this->isConnected)
            $this->connect();

        $table = 'domain_link_alert';

        $query = '';
        foreach ($alerts as $alert => $value) {
            $query .= 'INSERT INTO ' . $table . ' (`domain_link_id`, `alert`, `date`)
                VALUES ("' . $linkId . '","' . $alert . '","' . date('Y-m-d') . '");';
        }

        try {
            $this->DB->exec($query);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    public function startTransaction()
    {

    }

    public function setIp($domainId, $ipAddress, $cBlock) {
        if (!$this->isConnected)
            $this->connect();

        $table = 'domain';
        try {
            $this->DB->exec('UPDATE ' . $table . '
                SET `ip` = ' . ($ipAddress ? ('"' . $ipAddress . '"') : 'NULL') . ', `ip_c_block` = ' . ($ipAddress ? ('"' . $cBlock . '"') : 'NULL') . '
                WHERE id = ' . $domainId . ';');
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    public function commitTransaction()
    {
        $this->DB->commit();
    }

    public function rollback()
    {
        $this->DB->rollback();
    }

    public function out($message)
    {
        echo "{$this->name}#{$this->id}: " . $message . PHP_EOL;
    }

    /*
    private function gedDaysBeforeNextCheck($lastGoodResultAt)
    {
        $goodResultAt = strtotime($lastGoodResultAt) ?: time();
        $lastCheckTime = ($goodResultAt - time()) / (3600 * 24);
        if ($lastCheckTime > 180) {
            $checkAfterDays = 90;
        } else if ($lastCheckTime > 21) {
            $checkAfterDays = 30;
        } else {
            $checkAfterDays = 7;
        }

        return $checkAfterDays;
    }
    */
}
